import { SettingDrawer } from "@ant-design/pro-layout";
import { PageLoading } from "@ant-design/pro-layout";
import { history, Link } from "umi";
import RightContent from "@/components/RightContent";
import Footer from "@/components/Footer";
import { currentUser as queryCurrentUser } from "./services/ant-design-pro/api";
import { BookOutlined, LinkOutlined } from "@ant-design/icons";
import defaultSettings from "../config/defaultSettings";
import { Scrollbars } from 'react-custom-scrollbars';
import IconFont from "./components/IconFont";
import { useRef } from "react";


const isDev = process.env.NODE_ENV === "development";
const loginPath = "/user/login";
const headlessPath = "/user/headless"
/** 获取用户信息比较慢的时候会展示一个 loading */

export const initialStateConfig = {
  loading: <PageLoading />,
};
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState() {
  const fetchUserInfo = async () => {
    // try {
    //   const msg = await queryCurrentUser();
    //   return msg.data;
    // } catch (error) {
    //   history.push(loginPath);
    // }
    if (!localStorage.getItem("NAME")) {
      history.push(loginPath);
    }


    return {
      name: localStorage.getItem("NAME")
    };
  }; // 如果不是登录页面，执行

  if (history.location.pathname !== loginPath && history.location.pathname !== headlessPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
      component: "Canvas",
      selectedKeys: [],
      selectedIndexArr: []
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
} // ProLayout 支持的api https://procomponents.ant.design/components/layout

function ScrollChild({ initialState, setInitialState, children, location }) {
  let scrollRef = useRef();
  const nofooter = ["list", "preview", "headless"]

  return (<Scrollbars
    thumbMinSize={10}
    autoHide
    style={{ width: '100%', height: nofooter.some(it => location?.pathname?.includes(it)) ? "100vh" : 'calc( 100vh - 48px)' }}
    hideTracksWhenNotNeeded={true}
    ref={scrollRef}
    onScroll={(e) => {
      if (e.target.scrollTop > 300 && !initialState.showaction) {
        setInitialState((s) => ({ ...s, showaction: true }));
      } else if (e.target.scrollTop < 301 && initialState.showaction) {
        setInitialState((s) => ({ ...s, showaction: false }));
      }
    }}
  >
    <div style={{ minHeight: nofooter.some(it => location?.pathname?.includes(it)) ? "100vh" : "calc( 100vh - 48px)" }}>
      {children}

      <div className={"fixtotop"} style={{ transition: "all 0.4s", right: initialState.showaction ? 0 : -56 }} onClick={(e) => {
        scrollRef.current.view.scroll({
          top: 0,
          left: 0,
          behavior: 'smooth'
        });
      }}>
        <IconFont type="icon-totop" className="icon">
        </IconFont>
      </div>

    </div>
    {
      nofooter.some(it => location?.pathname?.includes(it)) ? null :
        <Footer></Footer>
    }

  </Scrollbars>);
}



export const layout = ({ initialState, setInitialState }) => {
  return {
    men: {
      locale: false
    },
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: null,
    onPageChange: () => {
      const { location } = history; // 如果没有登录，重定向到 login

      // if (!initialState?.currentUser && location.pathname !== loginPath) {
      //   history.push(loginPath);
      // }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        props.location?.pathname?.includes("/login") ?
          <>
            {children}
          </>
          :
          <ScrollChild initialState={initialState} setInitialState={setInitialState} {...props}>
            {children}
          </ScrollChild>
      );
    },
    ...initialState?.settings,
    logo: require("@/assets/logo_main.png")
  };
};
